var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser')
const session = require('express-session')
const frontApi = require('./routes/front/index');
const adminApi = require('./routes/admin/index');

var app = express();

// 模板引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//登录持久化
app.use(cookieParser('fun_blog_cookie'));
app.use(session({
  secret:'fun_blog_cookie',
  name:'session_id',
  resave:true,
  saveUninitialized:true,
  cookie:{
    maxAge:60*1000*30
  }

}))
//静态资源访问配置
app.use(express.static(path.join(__dirname, 'public')));
// 初始化连接mongodb
const mongodb = require('./core/mongodb')
mongodb.connect()
// 初始化前后台api
frontApi(app)
adminApi(app)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
